package calvin.study.rabbitmq.mq;


import java.util.Date;

import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import calvin.study.rabbitmq.dao.RabbitMqMessageLogDao;
import calvin.study.rabbitmq.model.order.Order;
import calvin.study.rabbitmq.model.rabbitmq.enums.OrderSendStatusEnum;
@Component
public class RabbitOrderSender {
    //自动注入RabbitTemplate模板类
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RabbitMqMessageLogDao RabbitMqMessageLogDao;

    //回调函数: confirm确认
    final RabbitTemplate.ConfirmCallback  confirmCallback = new RabbitTemplate.ConfirmCallback() {
    	
    	 @Override
         public void confirm(CorrelationData correlationData, boolean ack, String cause) {
             System.err.println("消息唯一的id correlationData: " + correlationData);
             String messageId = correlationData.getId();
             if(ack){
                 //如果confirm返回成功 则进行更新
             	RabbitMqMessageLogDao.changeBrokerMessageLogStatus(messageId, OrderSendStatusEnum.ORDER_SUCCESS.getCode(), new Date());
             } else {
                 //失败则进行具体的后续操作:重试 或者补偿等手段
                 System.err.println("异常处理...");
             }
         }
    };

    //发送消息方法调用: 构建自定义对象消息
    public void sendOrder(Order order) throws Exception {
    	// 通过实现 ConfirmCallback 接口，消息发送到 Broker 后触发回调，确认消息是否到达 Broker 服务器，也就是只确认是否正确到达 Exchange 中
        rabbitTemplate.setConfirmCallback(confirmCallback);
        
        //消息唯一ID
        CorrelationData correlationData = new CorrelationData(order.getOrderId());
        rabbitTemplate.convertAndSend("order_exchange", "order.abcd", order, correlationData);
    }
}
